package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R senMsm(@PathVariable String phone) //验证码需要我们自己 生成
    {
        //1.从redis获取验证码 、限制用户五分钟内不能再次发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
    }

        //redis 获取不到 进行阿里云发送
        String fourBitRandom = RandomUtil.getFourBitRandom();

        Map<String,Object> param = new HashMap<>();
        param.put("code",fourBitRandom);

        //调用service发送短信的方法
//        boolean isSend = msmService.send(param, phone);

//        if(isSend)
        if(!StringUtils.isEmpty(fourBitRandom))
        {
            //redis设置五分钟过期
//            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//五分钟的时长
            redisTemplate.opsForValue().set(phone,fourBitRandom,5, TimeUnit.MINUTES);//五分钟的时长
            return  R.ok().data("code",fourBitRandom);
        }
        return  R.error().message("短信发送失败");
    }
}
